<template lang='pug'>
.edit
  form.edit-address-form(action="")
    .title
      span 地址信息
      a.delbtn(href="javascript:;",v-if="detailAddress.addressId",@click="delAddressSure") 删除
    .group(title="地址信息")
      .cell#selCity.is-link(title="所在城市：",@click="choiceCity")
        .label 所在城市：
        .slotdiv
          input#sel-city(type="text",readonly,v-model="beforePosition.cityName")
        .icon
      .cell.is-link(title="所在小区：",@click.stop="selXQ")
        .label 所在小区：
        .slotdiv
          input(type="text",placeholder="选择所在小区",readonly,v-model="beforePosition.poiName").cellvalue
        .icon
      template(v-if="loudong")
        .cell.is-link(title="详细区域：",@click="sAdsSelect").cell
          .label 详细区域：
          .slotdiv
            input(type="text",placeholder="几期\\片区\\楼栋\\单元等",readonly,v-model="detailAddress.pathName").cellvalue
          .icon
        .cell
          .label 门牌号：
          .slotdiv
            input#houseNumber(type="text",placeholder="请填写（如601）",v-model="detailAddress.houseNumber",@focus="inputfocus('houseNumber')",ref='houseNumber')
      template(v-else)
        .cell
          .label 详细地址：
          .slotdiv
            input#houseNumber(type="text",placeholder="请填写详细地址",v-model="detailAddress.houseNumber",@focus="inputfocus('detailAD')",ref='detailAD')
    .title
      span 联系人信息
    .group
      .cell(title="联系人姓名：")
        .label 联系人姓名：
        .slotdiv.my-address-reciver-input(ref='contactName')
          x-input(placeholder="请输入2-6位中文字符",v-model="detailAddress.userName",:min="2",:max="6",@on-focus="inputfocus('contactName')").cellinput
          //- input(type="text",placeholder="请输入联系人姓名",v-model="detailAddress.userName").cellinput
      .cell
        .label 联系人电话：
        .slotdiv.my-address-reciver-input(ref='contactPhone')
          x-input(name="mobile",placeholder="请输入联系人电话",v-model="detailAddress.phone",keyboard="number",:max="11",@on-focus="inputfocus('contactPhone')").cellinput          
          //- input(type="text",placeholder="请输入联系人电话",v-model="detailAddress.phone").cellinput
  .savebtn(@click="saveInformation") 保存
  //- popup(v-model="show1",height="30%")
  //-   picker.citypicker(:data="citys",v-model="city",@on-change='change')
  ads-select(v-show="showAdsSelect",v-if="areaData.length !=0",v-on:closeselectAds="setAds",:adata="areaData",:anav = "navData")
  citySelect(v-show="showCitySelect",v-if="citys.length !=0",v-on:closeselectCity="setCity",:adata="citys")
</template>
<script>
import { Cell, CellBox, Group, Popup, Picker, XInput } from 'vux'
import { mapGetters } from 'vuex'
import AdsSelect from './adsSelect'
import citySelect from './citySelect'
import fetch from '@/config/fetch'
import { snxd } from '@/config/env'
import { setSelectedPositionCookie } from '@/config/utils'
import $ from 'webpack-zepto'
export default {
    data() {
        return {
            show1: false,
            cityName: '',
            selmdmCityCode: '1000173',
            curPoiName: '',
            district: '',//具体地址
            houseNumber: '',//门牌号
            name: '',
            phoneNumber: '',
            navTitle: ['期/片区', '楼栋', '单元', '房间'],
            city: [''],
            citys: [],
            areaData: [], // 地址选择信息
            navData: [], // 地址选择nav信息
            showAdsSelect: false,
            showCitySelect: false,
            loudong: true, //是否维护到楼栋
        }
    },
    created() {
        this.getAreaData();
        this.getNavData();
        this.getCitys();
    },
    methods: {
        // 修复键盘弹出后挡住输入框，获得焦点后传入ref，计算dom到顶部的高度.
        inputfocus(name) {
            var top = $(this.$refs[name]).offset().top - 50;
            if (top && top > 0) {
                setTimeout(function () {
                    $('body').scrollTop(top);
                }, 500)
            }
        },
        choiceCity() {
            let cartLink = this.$route.query.cartLink
            if (!!cartLink) {
                return
            }
            this.showCitySelect = true;
        },
        // 选择小区
        selXQ() {
            let cartLink = this.$route.query.cartLink
            if (!!cartLink) {
                this.$router.push('/address/all/edit?cartLink=cart2')
            }else{
                this.$router.push('/address/all/edit')
            }
        },
        // 删除
        delAddressSure() {
            let self = this
            if (this.defaultAddress.addressId == this.detailAddress.addressId) {
                AlertBox({
                    msg: '此地址为当前使用地址，无法删除！',
                    type: 'onceConfirm',
                });
                return
            }
            AlertBox({
                type: 'doubleBtn',
                msg: '确定删除此收货地址么？',
                confirm: function () {
                    self.delAddress()
                }
            });
        },
        delAddress() {
            fetch({
                url: `${snxd}/address/delete.do`,
                params: { addressId: this.detailAddress.addressId },
                type: 'post'
            }).then(res => {
                if (res.code == '1') {
                    if (res.data.isSuccess) {
                        // 删除成功
                        this.$router.go(-1)
                    }
                } else {
                    AlertBox({
                        msg: res.msg,
                        type: 'onceConfirm',
                    });
                }
            })
        },
        sAdsSelect() {
            if (!this.beforePosition.poiName) {
                AlertBox({
                    msg: '请先选择所在小区',
                    type: 'onceConfirm',
                });
                return
            }
            this.showAdsSelect = true
        },
        change(value) {
            this.city = value;
            this.selectCity = this.city[0]
            let position = Object.assign({}, this.$store.state.beforePosition, { mdmCityCode: this.selmdmCityCode })
            this.$store.commit('setBeforePosition', position)
        },
        getCitys() {
            fetch({
                url: `${snxd}/city/getCitys.html`,
                params: {}
            }).then((res) => {
                this.citys = res.data[0].citys
            })
        },
        getAreaData() {
            fetch({
                url: `${snxd}/poiLevel/poiDetailList_${this.beforePosition.poiId}.do`,
                params: {}
            }).then((res) => {
                console.log(res)
                if (res.data.length == 0) {
                    this.loudong = false;
                    return
                }
                this.areaData = res.data
            })
        },
        getNavData() {
            fetch({
                url: `${snxd}/poiLevel/poiLevelList_${this.beforePosition.poiId}.do`,
                params: {}
            }).then((res) => {
                if (res.data.length == 0) {
                    this.loudong = false;
                    return
                }
                this.navData = res.data
            })
        },
        setCity() {
            this.showCitySelect = false;
        },
        setAds() {
            this.showAdsSelect = false;
        },
        saveInformation() {
            if (this.loudong && !this.detailAddress.pathName) {
                AlertBox({
                    msg: '详细区域不能为空',
                    type: 'onceConfirm',
                });
                return
            }

            if (!this.detailAddress.houseNumber) {
                AlertBox({
                    msg: '详细地址不能为空',
                    type: 'onceConfirm',
                });
                return
            }

            let url
            // 姓名验证
            var reg = /[\u4E00-\u9FA5]{2,7}/g;
            if (!this.detailAddress.userName) {
                AlertBox({
                    msg: '请填写收货人姓名',
                    type: 'onceConfirm',
                });
                return
            }
            if (!reg.test(this.detailAddress.userName)) {
                AlertBox({
                    msg: '联系人姓名请输入2-6位中文字符',
                    type: 'onceConfirm',
                });
                return
            }

            // 验证电话
            var regtel = /^1\d{2}[0-9*]{4}\d{4}$/;
            if (!regtel.test(this.detailAddress.phone)) {
                AlertBox({
                    msg: '请输入正确电话号码',
                    type: 'onceConfirm',
                });
                return
            }

            let newData = {
                userName: this.detailAddress.userName,
                phone: this.detailAddress.phone,
                provCode: this.beforePosition.provCode,
                cityCode: this.beforePosition.cityCode,
                poiId: this.beforePosition.poiId,
                poiPath: this.detailAddress.poiPath,
                pathName: this.detailAddress.pathName,
                houseNumber: this.detailAddress.houseNumber
            }
            if (this.detailAddress.addressId) {
                // 修改地址信息
                Object.assign(newData, { addressId: this.detailAddress.addressId })
                url = `${snxd}/address/update.do`
            } else {
                // 创建地址信息
                if (!this.loudong) {
                    Object.assign(newData, {
                        poiPath: '',
                        pathName: '',
                    })
                }
                url = `${snxd}/address/create.do`
            }

            fetch({
                url: url,
                params: newData,
                type: 'post'
            }).then(res => {
                if (res.code == "1") {
                    if (this.$route.params.type == 'cart2') {
                        this.setAddress2(newData, (res.data.addressId || this.detailAddress.addressId))
                    } else {
                        this.$router.go(-1)
                    }
                } else {
                    AlertBox({
                        msg: res.msg,
                        type: 'onceConfirm',
                    });
                }
            })
        },
        setAddress2(item, addressId) {
            let p = {
                storeLocation: this.beforePosition.storeLocation || this.position.storeLocation,
                cityName: this.beforePosition.cityName,
                cityCode: item.cityCode,
                storeName: this.beforePosition.storeName || this.position.storeName,
                storeCode: this.beforePosition.storeCode || this.position.storeCode,
                poiId: item.poiId,
                poiName: this.beforePosition.poiName,
            }
            let id = {
                addressId: addressId
            }
            setSelectedPositionCookie(p)
            this.$store.commit('setPosition', p);
            this.$store.commit('setUserInfo', p)
            this.$store.commit('setDefaultAddress', id);
            let link = this.$route.query.cartLink
            this.$router.replace({ path: link })
        },
    },
    components: {
        AdsSelect,
        citySelect,
        XInput
    },
    computed: {
        ...mapGetters([
            'beforePosition', 'detailAddress', 'position', 'defaultAddress'
        ])
    }
}
</script>
<style lang='scss' scoped>
@import '../tool.scss';
.main {
    position: relative;
}

.edit {
    // padding-top: _(20);
    form {
        .title {
            color: #999;
            width: 100%;
            height: _(80);
            line-height: _(80);
            text-indent: _(20);
            font-size: _(28);
            border-bottom: 1px solid #e3e3e3;
            .delbtn {
                display: block;
                color: #ff7c33;
                height: _(80);
                line-height: _(80);
                float: right;
                margin-right: _(20);
            }
        }
        .group {
            width: 100%;
            background-color: #fff;
            .cell {
                width: 100%;
                height: _(88);
                line-height: _(88);
                border-bottom: 1px solid #e3e3e3;
                font-size: _(28);
                position: relative;
                .label {
                    width: _(229);
                    height: 100%;
                    float: left;
                    text-indent: _(20);
                }
                .slotdiv {
                    display: block;
                    width: toRem(450);
                    float: left;
                    height: 100%;
                    overflow: hidden;
                    input {
                        border: 0;
                        width: toRem(450);
                    }
                }
                .icon {
                    display: block;
                    width: _(12);
                    height: _(20);
                    position: absolute;
                    top: _(33);
                    right: _(28);
                    background-image: url('/static/images/rightb.png');
                    background-size: 100% 100%;
                }
            }
        }
    }
}

.citypicker {
    width: 100%;
    height: 100%;
}

.slotinput {
    position: absolute;
    top: 0;
    left: toRem(229);
    width: toRem(400);
    overflow: hidden;
    height: toRem(108);
    line-height: toRem(108);
    z-index: 10
}

.savebtn {
    display: block;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: toRem(94);
    color: #fff;
    line-height: toRem(94);
    font-size: toRem(36);
    text-align: center;
    background-color: #ff7d37;
}
</style>

<style>
.my-address-reciver-input {
    width: 10rem !important;
}
</style>
